<template>
  <view>
    <view class="address-management">
      <radio-group
        class="radio-group"
        @change="radioChange"
        v-if="addressList.length"
      >
        <view
		
          class="item borRadius14"
          v-for="(item, index) in addressList"
          :key="index"
		  @tap.stop="select(item)"
        >
          <view class="address" @click="goOrder(item.id)">
            <view class="consignee"
              >{{ item.consigneeName }}<text class="phone">{{ item.consigneeMobile }}</text>
              <view class="default_wrapper" v-if="item.itemType === 0"
                >默认</view
              >
            </view>
            <view class="province_wrapper"
              >{{ item.consigneeProvince }}{{ item.consigneeCity }}{{ item.consigneeArea
              }}{{ item.consigneeAddress }}</view
            >
          </view>
          <view class="operation acea-row row-between-wrapper">
			  <view class="">
			  	<text v-if="item.defaultFlag==1">默认地址</text>
			  </view>
           
          
            <view class="acea-row row-middle but_wrapper">
              <view class="edit_" @click.stop="editAddress(item)">编辑</view>
              <view class="delete_" @click.stop="delAddress(item, index)">删除</view>
            </view>
          </view>
        </view>
      </radio-group>
      <view class="noCommodity" v-if="addressList.length === 0">
        <view
          class="pictrue"
          style="
            width: 100%;
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
			margin-top: 30vh;
          "
        >
          <image src="/static/None/node_address.png" />
          <text>暂无地址喔~</text>
        </view>
      </view>
      <view style="height: 120rpx"></view>
    </view>
    <view class="footer acea-row row-between-wrapper">
      <view class="addressBnt bg-color" @click="addAddress"
        ><text class="iconfont icon-tianjiadizhi"></text>新增地址</view>
      <!--      <view class='addressBnt wxbnt' @click='getWxAddress'><text class='iconfont icon-weixin2'></text>导入微信地址</view>-->
     
        <!--   <view class="addressBnt bg-color" @click="addAddress"
           ><text class="iconfont icon-tianjiadizhi"></text>添加新地址</view
           > -->
    </view>
    <!-- #ifdef MP -->
    <!-- <authorize @onLoadFun="onLoadFun" :isAuto="isAuto" :isShowAuth="isShowAuth" @authColse="authColse"></authorize> -->
    <!-- #endif -->
    <!--    <home></home>-->
  </view>
</template>

<script>
// import {
//   getAddressList,
//   setAddressDefault,
//   delAddress,
//   editAddress,
//   postAddress
// } from '@/api/user.js';
import { toLogin } from "@/libs/login.js";
import { mapGetters } from "vuex";
// #ifdef MP
// import authorize from '@/components/Authorize';
// #endif
import { getConsigneeInfo,delConsigneeInfo,selAddrApi, updateAddr, delAddrDelete } from "@/api/address";
export default {
  components: {
     // #ifdef MP
    // authorize,
    // #endif
  },
  data() {
    return {
      addressList: [],
      cartId: "",
      pinkId: 0,
      couponId: 0,
      loading: false,
      loadend: false,
      loadTitle: "加载更多",
      page: 1,
      limit: 20,
      isAuto: false, //没有授权的不会自动授权
      isShowAuth: false, //是否隐藏授权
      bargain: false, //是否是砍价
      combination: false, //是否是拼团
      secKill: false, //是否是秒杀,
      userId: "",
      addressObj: {
        id: 0,
        memberId: uni.getStorageSync("userInfoServer")
          ? uni.getStorageSync("userInfoServer").userId
          : "",
        receiver: "",
        mobile: "",
        addr: "",
        province: "",
        city: "",
        area: "",
        itemType: 0,
		selecttype:false,
      },
    };
  },
  computed: mapGetters(["isLogin"]),
  watch: {
    isLogin: {
      handler: function (newV, oldV) {
        if (newV) {
          // this.getUserAddress(true);
        }
      },
      deep: true,
    },
  },
  onLoad(options) {
	  this.selecttype=options.type&&options.type==1?true:false
	  
	  if (!uni.getStorageSync("userId")) {
	    // 弹窗告诉用户去登录
	    uni.showModal({
	      title: "温馨提示",
	      content: "此时此刻需要您登录喔~",
	      // showCancel: false,
	      confirmText: "去登录",
	      cancelText: "再逛会",
	      success: (res) => {
	        if (res.confirm) {
	          uni.navigateTo({
	            url: "/pages/empower/mp-weixin",
	          });
	        }
	        if (res.cancel && getCurrentPages().length > 1) {
	          uni.navigateBack();
	        }
	        
	      },
	    });
	  }
	  
  },
  onShow: function () {
    let that = this;
    that.getAddressList(true);
  },
  methods: {
	  select(item){
			  
		  if(!this.selecttype){
			  return
		  }
		  
		  let pages = getCurrentPages();//获取页面实例
		  				let nowPage = pages[pages.length - 1];//当前页面实例
		  				let prevPage = pages[pages.length - 2];//上一级页面实例
		  				let carobj = item
		  				//在这个地方向上一个页面的实例的函数传递一个参数
		  				//Backcardaa函数是A页面中封装的函数
		  				prevPage.$vm.selectaddress(carobj)
		  				uni.navigateBack({
		  					delta: 1
		  				})
	  },
    onLoadFun: function () {
      this.getAddressList();
    },
    // 授权关闭
    authColse: function (e) {
      this.isShowAuth = e;
    },
    /*
     * 导入微信地址（小程序）
     */
    getWxAddress: function () {
		// chiak去掉
		return
      let that = this;
      uni.authorize({
        scope: "scope.address",
        success: function (res) {
          uni.chooseAddress({
            success: function (res) {
              let addressP = {};
              addressP.province = res.provinceName;
              addressP.city = res.cityName;
              addressP.district = res.countyName;
              addressP.cityId = 0;
              // editAddress({
              //   address: addressP,
              //   isDefault: true,
              //   realName: res.userName,
              //   postCode: res.postalCode,
              //   phone: res.telNumber,
              //   detail: res.detailInfo,
              //   id: 0
              //   //type: 1//区别城市id（导入微信地址无城市id需要后台自己查找）;
              // }).then(res => {
              //   that.$util.Tips({
              //     title: "添加成功",
              //     icon: 'success'
              //   }, function() {
              //     that.getAddressList(true);
              //   });
              // }).catch(err => {
              //   return that.$util.Tips({
              //     title: err
              //   });
              // });
            },
            fail: function (res) {
              if (res.errMsg == "chooseAddress:cancel")
                return that.$util.Tips({
                  title: "取消选择",
                });
            },
          });
        },
        fail: function (res) {
          uni.showModal({
            title: "您已拒绝导入微信地址权限",
            content: "是否进入权限管理，调整授权？",
            success(res) {
              if (res.confirm) {
                uni.openSetting({
                  success: function (res) {
                    console.log(res.authSetting);
                  },
                });
              } else if (res.cancel) {
                return that.$util.Tips({
                  title: "已取消！",
                });
              }
            },
          });
        },
      });
    },
    /*
     * 导入微信地址（公众号）
     */
    getAddress() {
      let that = this;
      // that.$wechat.openAddress().then(userInfo => {
      //   // open();
      //   editAddress({
      //     realName: userInfo.userName,
      //     phone: userInfo.telNumber,
      //     address: {
      //       province: userInfo.provinceName,
      //       city: userInfo.cityName,
      //       district: userInfo.countryName,
      //       cityId: 0
      //     },
      //     detail: userInfo.detailInfo,
      //     postCode: userInfo.postalCode,
      //     isDefault: true
      //   })
      //       .then(() => {
      //         that.$util.Tips({
      //           title: "添加成功",
      //           icon: 'success'
      //         }, function() {
      //           // close();
      //           that.getAddressList(true);
      //         });
      //       })
      //       .catch(err => {
      //         // close();
      //         return that.$util.Tips({
      //           title: err || "添加失败"
      //         });
      //       });
      // });
    },
    /**
     * 获取地址列表
     *
     */
    getAddressList: async function (isPage) {
      let that = this;
      if (isPage) {
        that.loadend = false;

        //地址管理
        const res = await getConsigneeInfo({userId:uni.getStorageSync("userId")}) ;
		// let resobj= res)
		
        if (res.result == 0) {
          this.addressList = res.consigneeInfoList;
        }
      }
    },
    /**
     * 设置默认地址
     */
    radioChange: async function (e) {
      console.log(e, "默认地址");
      let index = parseInt(e.detail.value),
        that = this;
      console.log(index, "index");
      let address = this.addressList[index];
      console.log(address, "address");
      if (address == undefined)
        return that.$util.Tips({
          title: "您设置的默认地址不存在!",
        });
      const data = {
        id: address.id,
        memberId: address.memberId,
        receiver: address.receiver,
        mobile: address.mobile,
        addr: address.addr,
        province: address.province,
        city: address.city,
        area: address.area,
        itemType: 0,
      };
      const res = await updateAddr(data);
      console.log(res, "地址");
      if (res.code === 0) {
        that.$util.Tips({
          title: "设置成功",
          icon: "success",
          duration: 2000,
        });
        this.addressList.forEach((item) => {
          if (item.id === res.data.id) {
            item.itemType = res.data.itemType;
          } else {
            item.itemType = 1;
          }
        });
      } else {
        that.$util.Tips({
          title: res.msg,
        });
      }
    },
    /**
     * 编辑地址
     */
    editAddress: async function (item) {
      console.log(item, "item 编辑");
      const data = {
        consigneeInfoId: item.id,
        userId: uni.getStorageSync("userId"),
        consigneeName: item.consigneeName,
        consigneeMobile: item.consigneeMobile,
        consigneeProvince: item.consigneeProvince,
        consigneeCity: item.consigneeCity,
        consigneeArea: item.consigneeArea,
        consigneeAddress: item.consigneeAddress,
        defaultFlag: item.defaultFlag,
      };
      uni.navigateTo({
        url: "/pages/subpackage/address/index?address=" + encodeURIComponent(JSON.stringify(data)),
      });
    },
    /**
     * 删除地址
     */
    async delAddress(item, index) {
      console.log(item, index);
	  var dateinfo={
		  userId:uni.getStorageSync("userId"),
		  consigneeInfoId:item.id
	  }
      const than = this;
      wx.showModal({
        title: "温馨提示",
        content: `是否确定删除该地址？`,
        confirmColor: "red", //确定文字的颜色
        async success(res) {
          if (res.confirm) {
            const resData = await delConsigneeInfo(JSON.stringify(dateinfo));
            if (resData.result == 0) {
              than.addressList.splice(index, 1);
              than.$util.Tips({
                title: "删除成功",
                icon: "success",
                duration: 2000,
              });
            } else {
              this.$util.Tips({
                title: resData.message,
              });
            }
          } else if (res.cancel) {
            console.log("用户点击取消");
          }
        },
      });
    },
    /**
     * 新增地址
     */
    addAddress: function () {
      // let cartId = this.cartId,
      //   pinkId = this.pinkId,
      //   couponId = this.couponId;
      // this.cartId = "";
      // this.pinkId = "";
      // this.couponId = "";
      uni.navigateTo({
        url: "/pages/subpackage/address/index",
      });
    },
    goOrder: function (id) {
      console.log(id, "地址");
    },
  },
  onReachBottom: function () {
    console.log("上拉加载");
    this.getAddressList();
  },
};
</script>

<style lang="scss" scoped>
.but_wrapper {
  > view {
    width: rpx(64);
    height: rpx(28);
    background: #ffffff;
    border-radius: rpx(14);
    border: rpx(1) solid #b2b2b2;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  > .edit_ {
    margin-right: rpx(8);
  }
}

.province_wrapper {
  font-size: rpx(12);
  font-weight: 400;
  color: #888888;
  margin-bottom: rpx(8);
}

.address-management {
  padding: 20rpx 30rpx;
}
.address-management.fff {
  background-color: #fff;
  height: 1300rpx;
}

.line {
  width: 100%;
  height: 3rpx;
  image {
    width: 100%;
    height: 100%;
    display: block;
  }
}
.address-management .item {
  background-color: #fff;
  margin-bottom: 20rpx;
  padding: rpx(16) rpx(17) rpx(8) rpx(12);
}

.address-management .item .address {
  //margin: rpx(16) rpx(17) rpx(8) rpx(12);
  border-bottom: 1rpx solid #eee;
  font-size: 28rpx;
  color: #282828;
}

.address-management .item .address .consignee {
  font-size: 28rpx;
  font-weight: bold;
  margin-bottom: 8rpx;
  display: flex;
  > .default_wrapper {
    background: rgba(250, 81, 81, 0.1);
    border-radius: rpx(8);
    font-size: rpx(10);
    font-weight: 400;
    color: #fa5151;
    margin-left: rpx(8);
    padding: rpx(1) rpx(5);
  }
}

.address-management .item .address .consignee .phone {
  margin-left: 25rpx;
}

.address-management .item .operation {
  height: 83rpx;
  font-size: 28rpx;
  color: #282828;
}

.address-management .item .operation .radio text {
  margin-left: 13rpx;
}

.address-management .item .operation .iconfont {
  color: #2c2c2c;
  font-size: 35rpx;
  vertical-align: -2rpx;
  margin-right: 10rpx;
}

.address-management .item .operation .iconfont.icon-shanchu {
  margin-left: 35rpx;
  font-size: 38rpx;
}

.footer {
  position: fixed;
  width: 100%;
  background-color: #fff;
  bottom: 0;
  height: 200rpx;
  padding: 0 30rpx;
  box-sizing: border-box;
}

.footer .addressBnt {
  width: 330rpx;
  height: 90rpx;
  border-radius: 50rpx;
  text-align: center;
  line-height: 90rpx;
  font-size: 30rpx;
  color: #fff;
}

.footer .addressBnt.on {
  width: 570rpx;
  margin: 0 auto;
}

.footer .addressBnt .iconfont {
  font-size: 35rpx;
  margin-right: 8rpx;
  vertical-align: -1rpx;
}

.footer .addressBnt.wxbnt {
  background-color: #fe960f;
}

.footer.acea-row.row-between-wrapper {
  .addressBnt {
    width: 100%;
  }
}

.pictrue {
  display: flex;
  flex-direction: column;
  > image {
    width: rpx(222);
    height: rpx(158);
  }
  > text {
    font-size: rpx(13);
    font-weight: 400;
    color: #b2b2b2;
  }
}
</style>
